<template>
  <div class="index">
    <div class="table-container">
      <div class="table-container__top">
        <div class="table-container__top--title">账号管理</div>
        <t-button theme="primary" @click="handleAdd">
          <template #icon><add-icon /></template>
          新建账号
        </t-button>
      </div>
      <div v-if="tableData?.list?.length > 0">
        <user-table ref="tableRef" :data="tableData" @ok="" @refresh-list="refresh"></user-table>
      </div>
      <div v-else class="table-container__empty">
        <img
          class="table-container__empty--img"
          src="@/assets/icons/svg/empty.svg"
          alt=""
        />
        <div class="table-container__empty--text">暂无内容</div>
      </div>
    </div>
  </div>
  <!-- 添加或修改用户对话框 -->
  <t-dialog
    placement="center"
    :header="title"
    :visible="dialogVisible"
    :confirm-btn="{
      content: '添加',
      theme: 'primary',
      loading: confirmLoading
    }"
    :on-confirm="onValidate"
    :on-close="close"
  >
    <t-form
      ref="formRef"
      :data="formData"
      :rules="rulesUser"
      label-width="80px"
      label-position="top"
      :requiredMark="false"
    >
      <t-form-item label="账户名称" name="userName">
        <t-input v-model="formData.userName" placeholder="请输入" />
      </t-form-item>
      <t-form-item label="公司名称" name="companyName">
        <t-input v-model="formData.companyName" placeholder="请输入" />
      </t-form-item>
      <t-form-item label="姓名" name="nickName">
        <t-input v-model="formData.nickName" placeholder="请输入" />
      </t-form-item>
      <t-form-item label="角色类型" name="roleId">
        <!-- <el-input v-model="form.role" placeholder="请输入" /> -->
        <t-select
          v-model="formData.roleId"
          :options="roleTypeOptions"
          placeholder="请选择云角色类型"
          clearable
          @focus="onFocus"
          @blur="onBlur"
        ></t-select>
      </t-form-item>
      <t-form-item label="评估模型" name="assessType" v-if="formData.roleId == 15">
        <t-select
          v-model="formData.assessType"
          :options="assessModelOptions"
          placeholder="请选择评估模型"
          clearable
          @focus="onFocus"
          @blur="onBlur"
        ></t-select>
      </t-form-item>
      <t-form-item label="密码" name="password">
        <t-input v-model="formData.password" placeholder="请输入" />
      </t-form-item>
      <t-form-item label="是否可用" name="status">
        <t-switch v-model="formData.status" :customValue="['0','1']"> </t-switch>
      </t-form-item>
    </t-form>
  </t-dialog>
</template>
<script setup>
import { AddIcon } from "tdesign-icons-vue-next";
import UserTable from "@/views/components/table/UserTable.vue";
import { saveUser, getUserList } from "@/api/sjhg/user";
import { ref, onMounted } from "vue";
import { MessagePlugin } from "tdesign-vue-next";

//---------------------------------列表--------------------------------------------
const tableData = ref({});
const tableRef = ref(null)
const confirmLoading = ref(false)
onMounted(async() => {
  await queryUserList();
})

let params = {
  pageNum :1,
  pageSize : 10,
  sortField: 'update_time',
  sortOrder: 'DESC',
}
const goRefreshData = ref(true)
const refresh = (changeParams) =>{
  if(changeParams?.pagination){
    goRefreshData.value = false
    params.pageNum = changeParams.pagination.current
    params.pageSize = changeParams.pagination.pageSize
  }else if(changeParams?.sorter){
    params.pageNum = 1
    goRefreshData.value = true
    params.sortOrder = changeParams?.sorter.descending ? 'DESC':'ASC'
    if(changeParams?.sorter.sortBy === 'updateTime'){
      params.sortField = 'update_time'
    }else if(changeParams?.sorter.sortBy === 'status'){
      params.sortField = 'status'
    }
  }else{
    goRefreshData.value = true
    params.pageNum = 1
    params.sortField = 'update_time'
    params.sortOrder = 'DESC'
  }
  queryUserList();
}

// 获取用户列表
const queryUserList = () => {
    getUserList(params)
      .then((res) => {
        if (res.code == 200) {
          tableData.value = res.data || {}
          if(goRefreshData.value){
            if (tableRef.value && typeof tableRef.value.refreshData === 'function') {
              tableRef.value.refreshData(tableData.value.total)
            }
          }
        }
      });
  }

//--------------------------------新建弹框---------------------------------------------
const dialogVisible = ref(false);
const title = ref();
const handleAdd = (row) => {
  dialogVisible.value = true;
  title.value = "新建账号";
};
const formRef = ref(null);
const initialFormData = {
  userName: "",
  companyName: "",
  nickName: "",
  roleId: null,
  assessType: 0,
  password: "",
  status: "0",
};

const formData = ref({ ...initialFormData });
const passwordValidator = (val) => {
  const patten = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{9,}$/ ;
  if (val.length < 6) {
    return {
      result: false,
      message: "密码不低于6位",
      type: "warning",
    };
  }
  return {
    result: true,
  };
};
const rulesUser = {
  userName: [
    { required: true, message: "请输入账户名称", type: "error", trigger: "blur" },
    {
      min: 2,
      message: "至少需要两个字",
      type: "error",
      trigger: "blur",
    },
  ],
  companyName: [{ required: true, message: "请输入公司名称", type: "error" }],
  nickName: [{ required: true, message: "请输入姓名", type: "error" }],
  roleId: [{ required: true, message: "请选择角色类型", type: "error" }],
  assessType: [{ required: true, message: "请选择评估模型", type: "error" }],
  password: [
    { required: true, message: "请输入密码", type: "error" },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{9,}$/, message: '字母+数字+字符，位数要大于8位' },
    // { validator: passwordValidator },
  ],
};
const roleTypeOptions = [
  {
    label: "用户角色",
    value: 14,
  },
  {
    label: "评估角色",
    value: 15,
  },
];
const assessModelOptions = [
  {
    label: "DCMM",
    value: 0,
  },
  {
    label: "DSMM",
    value: 1,
  },
  {
    label: "数据合规",
    value: 2,
  },
];

//数据校验
const onValidate = () => {
  formRef.value?.validate().then((result) => {
    if (result === true) {
      //校验成功请求接口
      addUser();
    } 
  });
};

//新建账号
const addUser = async () => {
  confirmLoading.value = true
  try {
   await saveUser(formData.value)
      .then((res) => {
        if (res.code == 200) {
           //成功后  刷新列表
            MessagePlugin.success("新建成功");
            params.pageNum = 1

            goRefreshData.value = true
            queryUserList();
            
            dialogVisible.value = false;
            formRef.value.reset();
            formData.value = { ...initialFormData }; // 重置表单数据
        } 
        confirmLoading.value = false
      });
  } catch (error) {
    confirmLoading.value = false
  }
  if( confirmLoading.value){
    confirmLoading.value = false
  }
};

//关闭dialog
const close = () => {
  dialogVisible.value = false;
};
  
</script>
<style lang="scss" scoped>
.home-container {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}
.top-container {
  display: flex;
  height: 88px;
  background: var(--bg-white);
  border-radius: 8px;
  padding: 0 16px;
  position: relative;
  &__img {
    width: 56px;
    height: 56px;
    margin-right: 10px;
    margin-top: 16px;
  }
  &__title {
    color: #565960;
    font-size: 12px;
    margin-top: 16px;
  }

  &__value {
    color: #252931;
    font-size: 18px;
    font-weight: bold;
    margin-top: 16px;
  }
  &__btn {
    right: 16px;
    top: 16px;
    position: absolute;
    color: #1966ff;
  }
}
.index {
  padding: 0;
  margin-top: 16px;
}
.index-l {
  width: 76%;
  .userinfo {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 218px;
    border-radius: var(--border-radius-big);
    padding: 0px 20px 20px;
    margin-top: -38px;
    .bgSvg {
      color: var(--bg-white);
      position: absolute;
    }
    .portrait {
      position: relative;
      padding: 10px;
      .portrait-img {
        display: block;
        margin: 0 auto;
        width: 90px;
        height: 90px;
        border-radius: 50%;
        border: 1px solid var(--border-black-11);
      }
    }
    .wel {
      position: relative;
      font-size: 22px;
      font-weight: bold;
      margin: 2px 0 16px;
      width: 100%;
    }
    .role {
      position: relative;
      color: white;
      padding: 6px 8px;
      font-size: 12px;
      line-height: 1;
      border-radius: var(--border-radius-small);
    }
  }
  .data-view {
    margin: 0 0 0 16px;
    flex: auto;
    .data-view-wrap {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      margin: 30px -20px 0;
    }
    .data-view-item {
      border-left: 1px solid var(--bg-black-9);
      &:first-child {
        border: 0;
      }
    }
    .view-item-icon {
      width: 54px;
      height: 54px;
      overflow: hidden;
      background: var(--bg-black-11) center no-repeat;
      // background-repeat: no-repeat;
      border-radius: var(--border-radius-big);
      margin: 0 16px;
    }

    .view-item-title {
      color: var(--font-black-4);
      margin-bottom: 10px;
    }
    .view-item-num {
      font-size: 24px;
      font-weight: 500;
      color: var(--font-black);
      font-family: Bahnschrift-Regular, Bahnschrift;
    }
  }
}

.index-r {
  width: 23%;
  margin-left: 1%;

  .inedx-r-top {
    .companyName {
      line-height: 36px;
      font-size: 18px;
      font-weight: 500;
      color: var(--font-black);
      font-weight: bold;
    }

    .info {
      line-height: 24px;
      margin-top: 10px;
      color: var(--font-black-4);
      .fr {
        color: var(--font-black);
        font-weight: bold;
      }
    }
  }
  //   企业动态
  .card-title {
    background: linear-gradient(270deg, var(--color) 0%, var(--color-sub) 100%);
    padding-bottom: 10px;
  }
  .title-right-icon {
    width: 16px;
    height: 16px;
    line-height: 15px;
    background: var(--bg-white);
    border-radius: 50%;
    font-size: 12px;
    text-align: center;
  }
  .enterprise-card-item {
    overflow: hidden;
    border-radius: var(--border-radius-big);
    margin-top: -10px;
    padding-top: 0;
    .dynamics-item {
      border-bottom: 1px solid var(--border-black-10);
      padding: 16px 0;

      .info {
        span {
          vertical-align: middle;
        }
        .type {
          display: inline-block;
          max-width: 80px;
          padding: 4px 5px 3px;
          border-radius: 4px;
          font-size: 12px;
          margin-right: 8px;
        }
        .customer {
          background: #ecf5ff;
          color: #1869ff;
          border-color: #1869ff;
        }
        .staff {
          background: var(--color-light-10);
          color: var(--color);
          border-color: var(--color);
        }
        .type1 {
          padding: 5px 8px 4px;
          border-radius: 4px;
          background: none;
          font-size: 12px;
          border: 1px solid;
          flex: none;
        }
        .operatorName {
          font-size: 16px;
          color: var(--font-black);
          font-weight: 600;
        }
      }

      .operator {
        font-size: 12px;
        color: var(--font-black-4);
        margin-top: 10px;
        .nomal {
          color: var(--color);
        }
        .unnomal {
          color: #e34d59;
        }
      }
    }

    .g-tip-color {
      text-align: center;
      width: 100%;
      margin-top: 20px;
    }
  }

  .help-center {
    .help-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid var(--border-black-10);
      padding: 16px 0;
      // font-size: 12px;
      &:first-of-type {
        margin-top: -16px;
      }
      span {
        vertical-align: middle;
      }
      .left-icon {
        font-size: 26px;
        vertical-align: middle;
        margin-right: 10px;
      }
      .right-icon {
        font-size: 20px;
      }
    }
  }
}

.dialog-content {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  img {
    width: 260px;
    height: 260px;
  }
  span {
    font-size: 20px;
    line-height: 50px;
  }
}
</style>
